package com.example.sprintboot.controller;

import com.example.sprintboot.entity.Order;
import com.example.sprintboot.entity.OrderItem;
import com.example.sprintboot.entity.Payment;
import com.example.sprintboot.security.UserDetailsImpl;
import com.example.sprintboot.service.OrderService;
import com.example.sprintboot.dto.CreateOrderRequest;
import com.example.sprintboot.vo.OrderDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    // 获取当前登录用户ID
    private Integer getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetailsImpl) {
            return ((UserDetailsImpl) authentication.getPrincipal()).getUserId();
        }
        return null;
    }

    // 下单（创建订单）
    @PostMapping("/create")
    public Map<String, Object> createOrder(@RequestBody CreateOrderRequest req) {
        Integer userId = getCurrentUserId();
        if (userId == null) {
            return error("用户未登录");
        }
        if (req.getAddressId() == null || req.getItems() == null || req.getItems().isEmpty()) {
            return error("参数错误");
        }
        // DTO转OrderItem
        List<OrderItem> items = req.getItems().stream().map(dto -> {
            OrderItem item = new OrderItem();
            item.setProductId(dto.getProductId());
            item.setProductName(dto.getProductName());
            item.setProductPrice(dto.getProductPrice());
            item.setQuantity(dto.getQuantity());
            return item;
        }).collect(Collectors.toList());
        Order order = orderService.createOrder(userId, req.getAddressId(), items, req.getRemark());
        return success("下单成功", order);
    }

    // 查询当前用户所有订单
    @GetMapping("/list")
    public Map<String, Object> getOrderList() {
        Integer userId = getCurrentUserId();
        if (userId == null) {
            return error("用户未登录");
        }
        List<Order> orders = orderService.getOrdersByUserId(userId);
        return success("查询成功", orders);
    }

    // 查询订单详情
    @GetMapping("/{orderId}")
    public Map<String, Object> getOrderDetail(@PathVariable Integer orderId) {
        Integer userId = getCurrentUserId();
        if (userId == null) return error("用户未登录");
        OrderDetailVO vo = orderService.getOrderDetailVO(orderId, userId);
        if (vo == null) return error("订单不存在或无权限");
        return success("查询成功", vo);
    }

    // 支付订单（模拟支付）
    @PostMapping("/{orderId}/pay")
    public Map<String, Object> payOrder(@PathVariable Integer orderId, @RequestBody Map<String, String> req) {
        Integer userId = getCurrentUserId();
        if (userId == null) {
            return error("用户未登录");
        }
        String payMethod = req.get("payMethod");
        boolean ok = orderService.payOrder(userId, orderId, payMethod);
        if (ok) {
            return success("支付成功", null);
        } else {
            return error("支付失败");
        }
    }

    // 取消订单
    @PostMapping("/{orderId}/cancel")
    public Map<String, Object> cancelOrder(@PathVariable Integer orderId) {
        Integer userId = getCurrentUserId();
        if (userId == null) {
            return error("用户未登录");
        }
        boolean ok = orderService.cancelOrder(userId, orderId);
        if (ok) {
            return success("取消成功", null);
        } else {
            return error("取消失败");
        }
    }

    // 确认收货
    @PostMapping("/{orderId}/confirm")
    public Map<String, Object> confirmOrder(@PathVariable Integer orderId) {
        Integer userId = getCurrentUserId();
        if (userId == null) {
            return error("用户未登录");
        }
        boolean ok = orderService.confirmOrder(userId, orderId);
        if (ok) {
            return success("确认收货成功", null);
        } else {
            return error("操作失败");
        }
    }

    // 申请退款
    @PostMapping("/{orderId}/refund")
    public Map<String, Object> refundOrder(@PathVariable Integer orderId, @RequestBody Map<String, String> req) {
        Integer userId = getCurrentUserId();
        if (userId == null) {
            return error("用户未登录");
        }
        String reason = req.get("reason");
        if (reason == null || reason.trim().isEmpty()) {
            return error("退款原因不能为空");
        }
        boolean ok = orderService.refundOrder(userId, orderId, reason);
        if (ok) {
            return success("退款申请已提交", null);
        } else {
            return error("申请失败");
        }
    }

    // 查询支付记录
    @GetMapping("/{orderId}/payment")
    public Map<String, Object> getPayment(@PathVariable Integer orderId) {
        Integer userId = getCurrentUserId();
        if (userId == null) {
            return error("用户未登录");
        }
        Payment payment = orderService.getPaymentByOrderId(orderId);
        return success("查询成功", payment);
    }

    // 删除订单
    @PostMapping("/{orderId}/delete")
    public Map<String, Object> deleteOrder(@PathVariable Integer orderId) {
        Integer userId = getCurrentUserId();
        if (userId == null) return error("未登录");
        boolean ok = orderService.deleteOrder(userId, orderId);
        return ok ? success("删除成功", null) : error("删除失败");
    }

    private Map<String, Object> success(String msg, Object data) {
        Map<String, Object> map = new HashMap<>();
        map.put("success", true);
        map.put("message", msg);
        map.put("data", data);
        return map;
    }

    private Map<String, Object> error(String msg) {
        Map<String, Object> map = new HashMap<>();
        map.put("success", false);
        map.put("message", msg);
        return map;
    }
} 